function removeKDigits(num, k) {
  for (let i=0; i< k; i++) {
    let hasCut = false;
    for (let j=0; j < num.length -1; j++) {
      if (num.charAt(j) > num.charAt(j+1)) {
        num = num.substring(0, j) + num.substring(j+1, num.length);
        hasCut = false;
        break;
      }
    }
    if (!hasCut) {
      num = num.substring(0, num.length - 1)
    }
  }
  let start = 0;
  for (let j=0; j<num.length-1; j++) {
    if(num.charAt(j)!='0') {
      break;
    }
    start++;
  }
  num = num.substring(start, num.length);
  if (num.length == 0) {
    return '0'
  }
  return num;
}

function removeKDigitsV2(num ,k) {
  let newLength = num.length - k;
  let stack = new Array(num.length);
  let top = 0;
  for (let i=0; i<num.length;++i) {
    let c= num.charAt(i);
    while(top > 0 && stack[top-1] > c && k > 0) {
      top -=1;
      k -=1;
    }
    if ('0' ==c && top == 0) {
      newLength--;
      if(newLength <= 0){
          return "0";
      }
      continue;
    }
    stack[top++] = c;
  }
  return newLength <= 0 ? "0" : new String(stack)
}

console.log(removeKDigits("1593212", 2));

console.log(removeKDigits("1593212", 3));

